package com.example.broadcast.utils


import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.broadcast.LoginActivity

/**
 *@author cy
 *@date 2024/7/25
 *@apiNote
 */
open class BaseActivity : AppCompatActivity() {
    lateinit var receiver: ForceOfflineReceiver
    private val TAG = "BaseActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityController.addActivity(this)
        Log.d(TAG, "${javaClass.simpleName}创建了")

    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onResume() {
        super.onResume()
        val intentFilter = IntentFilter()
        intentFilter.addAction("com.example.broadcast.FORCE_OFFLINE")
        receiver = ForceOfflineReceiver()
        registerReceiver(receiver, intentFilter, RECEIVER_EXPORTED)
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(receiver)
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityController.removeActivity(this)
        Log.d(TAG, "${javaClass.simpleName}销毁了")

    }

    inner class ForceOfflineReceiver : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            if (p0 != null) {
                AlertDialog.Builder(p0).apply {
                    setTitle("warning")
                    setMessage("你被强制下线，请重新登录")
                    setCancelable(false)
                    setPositiveButton("OK") { _, _ ->
                        ActivityController.finishAll()
                        val i = Intent(p0, LoginActivity::class.java)
                        p0.startActivity(i)
                    }
                    show()
                }
            }
        }
    }

}